import Advert from '../models/advert'
import config from '../config'
import formidable from 'formidable'
import { basename } from 'path';
export function showadvert (req,res,next) {
  const page = Number.parseInt( req.query.page )
  const pageSize = 5
  Advert
    .find()
    .skip((page-1)*pageSize)
    .limit(pageSize)
    .exec((err,adverts) => {
      if(err) return next(err)
      Advert.count((err,count) => {
        if(err) return next(err)
        const totalPage = Math.ceil(count/pageSize)
        res.render('advert_list.html',{
          adverts,
          totalPage,
          page
        })
      })
    })
}
export function showadvertAdd (req,res,next) {
  res.render('advert_add.html')
}
export function advertAddPost(req,res,next){
  Formidable(req)
    .then((arr)=>{
      const [fields,files] = arr
      const body = fields
      body.image = basename(files.image.path)
      console.log(body)
      const advert = new Advert({
        title:body.title,
        image: body.image,
        link: body.link,
        start_time: body.start_time,
        end_time: body.end_time,
      })
      return advert.save()
    })
    .then(result => {
      res.json({
        err_code:0
      })
    })
    .catch(err => {
      next(err)
    })
}
function Formidable(req){
  return new Promise((resolve,reject)=>{
    const form = new formidable.IncomingForm()
    form.uploadDir = config.uploadDir
    form.keepExtensions = true;
    form.parse(req,(err,fields,files) => {
      if(err){
        reject(err)
      }else {
        resolve([fields,files])
      }
    })
  })
}
